import { message, Button, Switch, Divider, Popconfirm, DatePicker } from 'antd'
import React, { useState, useRef, useEffect} from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect } from 'umi'
import {getMemberRecord, saveOrUpdateEmployeeSecurity, updateInsuranceConfig, getInsuranceConfig} from '../service'
import moment from 'moment';
import {
  employeeStatusList,
  employeeTypeList,
  genderList,
  insuranceStatusList,
  InsuredStatusList
} from "@/utils/constant";
import CreatePersonForm from "@/pages/Security/LiabilityInsurance/LedgerList/components/CreatePersonForm";


const TableList = ({currentUser}) => {
  const { authorities } = currentUser;
  const actionRef = useRef();
  const formRef = useRef();
  const [personFormVisible, setPersonFormVisible] = useState(false);
  const [current, setCurrent] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [isOpen, setIsOpen] = useState(false);

  useEffect(()=>{
    formRef.current.setFieldsValue({status: '1'});
    getInsuranceConfig().then(res => {
      if (res.flag)
        setIsOpen(res.data.isOpen)
    })
  },[]);


  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 50,
      align: 'center',
      dataIndex: 'promotionId',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
    },
    {
      title: '工号',
      fixed: 'left',
      width: 70,
      align: 'center',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      fixed: 'left',
      width: 70,
      align: 'center',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '性别',
      align: 'center',
      dataIndex: 'gender',
      render: (text) => {
        const res = genderList.find((item) => item.value === text.toString());
        return res ? res.label : text
      },
      hideInSearch: true,
    },
    {
      title: '身份证',
      align: 'center',
      dataIndex: 'idcard',
      width: 110,
      hideInSearch: true,
    },
    {
      title: '用工类型',
      align: 'center',
      dataIndex: 'jobType',
      render: (text) => {
        return text!=='-' && employeeTypeList.find(e => parseInt(text) === e.value)?.label;
      },
      hideInSearch: true,
    },
    {
      title: '员工状态',
      align: 'center',
      dataIndex: 'employeestatus',
      valueEnum: {
        0: {text: employeeStatusList[0].label, status: 'default'},
        2: {text: employeeStatusList[1].label, status: 'default'},
        3: {text: employeeStatusList[2].label, status: 'default'},
        4: {text: employeeStatusList[3].label, status: 'default'},
        5: {text: employeeStatusList[4].label, status: 'default'},
        6: {text: employeeStatusList[5].label, status: 'default'},
        7: {text: employeeStatusList[6].label, status: 'default'},
        9: {text: employeeStatusList[7].label, status: 'default'},
        10: {text: employeeStatusList[8].label, status: 'default'},
        11: {text: employeeStatusList[9].label, status: 'default'},
      },
    },
    {
      title: '职级',
      align: 'center',
      dataIndex: 'jobLevel',
      hideInSearch: true,
    },
    {
      title: '入职日期',
      align: 'center',
      dataIndex: 'hiredate',
      render: (text) => {
        return text!=='-'?moment(text).format('YYYY-MM-DD'):''
      },
      hideInSearch: true,
    },
    {
      title: '公司',
      align: 'center',
      dataIndex: 'orgname',
    },
    {
      title: '部门',
      align: 'center',
      dataIndex: 'unitname',
      hideInSearch: true,
    },
    {
      title: '岗位',
      align: 'center',
      dataIndex: 'jobname',
      hideInSearch: true,
    },
    {
      title: '社保参保状态',
      align: 'center',
      dataIndex: 'type',
      valueEnum: {
        0: {text: InsuredStatusList[0].label, status: 'Default'},
        1: {text: InsuredStatusList[1].label, status: 'Success'},
      },
    },
    {
      title: '承保单位',
      align: 'center',
      dataIndex: 'companyName',
      width: 250
    },
    {
      title: '生效状态',
      align: 'center',
      dataIndex: 'status',
      valueEnum: {
        2: {text: insuranceStatusList[0].label, status: 'Default'},
        1: {text: insuranceStatusList[1].label, status: 'Success'},
      },
    },
    {
      title: '操作人工号',
      align: 'center',
      dataIndex: 'operaterCode',
      hideInSearch: true,
    },
    {
      title: '操作人',
      align: 'center',
      dataIndex: 'operateName',
    },
    {
      title: '操作日期',
      align: 'center',
      dataIndex: 'operateTime',
      /*renderFormItem: (item, props) => {
        return <DatePicker {...props} picker="month" />;
      },*/
      hideInSearch: true,
      render: (text) => {
        return text!=='-'?moment(text).format('YYYY-MM-DD'):''
      }
    },
    {
      title: '操作',
      fixed: 'right',
      align: 'center',
      width: 100,
      hideInTable: !isOpen,
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        record.status === 2 ?
          <a onClick={() => setPlanPerson([record])}>增员</a> :
          <a onClick={() => saveOrChangeStatus([record], 2)}>减员</a>
      ),
    },
  ];

  const rowSelection = {
    onChange: (rowKeys,rows) => {
      setSelectedRows(rows);
    }
  };

  const personHandleCancel = () => {
    setCurrent([]);
    setPersonFormVisible(false)
  };

  const personHandleSubmit = (values) => {
    saveOrUpdateEmployeeSecurity(values).then(res => {
      if (res.flag){
        message.success('增员成功！');
      }else {
        message.error(res.error);
      }
      personHandleCancel();
      actionRef.current.reload();
    })
  };

  const isHasDifferentStatus = (records, typeStr) => {
    if (records.length > 0) {
      let statusFlag = records[0].status;
      for (let item of records) {
        if (item.status !== statusFlag) {
          message.error(`请选择可${typeStr}的数据进行操作！`);
          return true;
        }
      }
    }else {
      message.error(`请选择列表数据进行操作！`);
      return true;
    }
  };

  const setPlanPerson = (records = []) => {
    setPersonFormVisible(true);
    setCurrent(records);
  };

  const saveOrChangeStatus = (records, type) => {
    if (isHasDifferentStatus(records,'减员'))
      return;
    saveOrUpdateEmployeeSecurity(records.map(item => ({...item, status: type}))).then(res => {
      if (res.flag) {
        message.success('减员成功!');
      } else {
        message.error(res.error);
      }
      actionRef.current.reload();
    })
  };

  const onControl = (value) => {
    let status = value ? 1 : 0;
    updateInsuranceConfig(status).then(res => {
      if (res.flag){
        setIsOpen(value);
        message.success('配置成功！')
      }else {
        message.error(res.error);
      }
      // actionRef.current.reload();
    })
  };

  const exportExcel = () => {
    // let date = moment(searchDate).format('YYYY-MM');
    window.open(`/hr-ssc/api/api-admin/export/exportInsurance`);
  };

  return (
    <PageHeaderWrapper>
          <ProTable
            formRef={formRef}
            actionRef={actionRef}
            rowKey="id"
            scroll={{ x: '150%' }}
            request={(params) => getMemberRecord(params)}
            rowSelection={{
              type: 'checkbox',
              ...rowSelection,
            }}
            columns={columns}
            search={{labelWidth: 'auto', defaultCollapsed: false}}
            toolBarRender={(action, {selectedRows}) => {
              let array = [
                <Button key='export' type="primary" onClick={() => exportExcel()}>导出</Button>
              ];
              authorities.indexOf('emp:gzzrx:opreateControl') > -1 && array.unshift([
                <div key='control'>增减员控制：<Switch defaultChecked onChange={onControl} checked={isOpen}/></div>
              ]);
              isOpen && array.push([
                <Button key='add' type="primary" onClick={() => setPlanPerson(selectedRows)}>增员</Button>,
                <Button key='downsizing' type="primary" onClick={() => saveOrChangeStatus(selectedRows,2)}>减员</Button>,
              ]);
              return array;
            }}
          />

      <CreatePersonForm
        current={current}
        visible={personFormVisible}
        onCancel={personHandleCancel}
        onSubmit={personHandleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(TableList)
